package com.zh.freechat.domain.message.repository;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zh.freechat.domain.message.entity.ChatMsgPO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @author ZH
 * @date 23:21 2021/5/15
 */
@Mapper
public interface ChatMsgPoRepository extends BaseMapper<ChatMsgPO> {

    @Update(value = "UPDATE ch_chat_msg SET status=#{status} WHERE id=#{msgId}")
    int updateStatus(@Param("msgId") long msgId, @Param("status") Integer status);

    @Update(value = """
            UPDATE ch_chat_msg 
            SET reads_sign = JSON_ARRAY_APPEND(reads_sign,'$',#{userId} ) 
            WHERE id=#{msgId}
            """)
    int addReadSign(@Param("msgId") long msgId, @Param("userId") String userId);

    @Update(value = """
            UPDATE ch_chat_msg 
            SET removes_sign = JSON_ARRAY_APPEND(removes_sign,'$',#{userId} ) 
            WHERE id=#{msgId}
            """)
    int addRemoveSign(@Param("msgId") String msgId, @Param("userId") String userId);

    /**
     * 查询历史消息列表
     * @param chatId 聊天关系ID
     * @param isGroup 是不是群聊消息
     * @param msgId 消息ID，根据此消息的createTime为基准去查询之前的消息
     * @param size 限制消息的条数
     * @return list
     */
    @Select(value = """
            SELECT * FROM ch_chat_msg 
             WHERE chat_id=#{chatId} and is_group=#{isGroup} 
             and create_time < IFNULL((SELECT create_time FROM ch_chat_msg WHERE id=#{msgId}),NOW()) 
             ORDER BY create_time desc LIMIT #{size} OFFSET 0 
            """)
    List<ChatMsgPO> findChatMsgByUserId(@Param("chatId") String chatId, @Param("isGroup") boolean isGroup, @Param("msgId") Long msgId, @Param("size") int size);
}
